package com.example.Windturbine.Service.Impl;

import com.alibaba.druid.sql.visitor.functions.Char;
import com.alibaba.excel.EasyExcel;
import com.example.Windturbine.Controller.ViewObject.Excel.PartExcel;
import com.example.Windturbine.Dao.ProductDOMapper;
import com.example.Windturbine.Dao.ProductInfoDOMapper;
import com.example.Windturbine.Dao.UserDOMapper;
import com.example.Windturbine.Dao.UserPasswordDOMapper;
import com.example.Windturbine.DataObject.UserDO;
import com.example.Windturbine.DataObject.UserPasswordDO;
import com.example.Windturbine.Error.BusinessException;
import com.example.Windturbine.Error.EmBusinessError;
import com.example.Windturbine.Listener.ExcelListener;
import com.example.Windturbine.Service.Model.ProductModel;
import com.example.Windturbine.Service.Model.UserModel;
import com.example.Windturbine.Service.ProductService;
import com.example.Windturbine.Service.UserService;
import com.example.Windturbine.Utils.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * @Author 丁永新
 * @Date 2021/12/11
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserDOMapper userDOMapper;

    @Resource
    UserPasswordDOMapper userPasswordDOMapper;

    @Autowired
    ProductService productService;

    @Resource
    ProductInfoDOMapper productInfoDOMapper;

    @Resource
    ProductDOMapper productDOMapper;


    @Override
    public UserModel getUserById(Integer id) throws BusinessException {
        UserDO userDO=userDOMapper.selectByPrimaryKey(id);

        UserModel userModel=new UserModel();
        if(userDO==null){
            throw new BusinessException(EmBusinessError.UNKNOWN_ERROR,"用户信息不存在！");
        }
        userModel.setId(userDO.getId());
        userModel.setEmail(userDO.getEmail());
        userModel.setUsername(userDO.getUsername());
        userModel.setName(userDO.getName());
        userModel.setTelphone(userDO.getTelphone());
        return userModel;
    }


    /**
     * 注册方法
     * @param userModel
     * @throws BusinessException
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
    public void register(UserModel userModel) throws BusinessException, FileNotFoundException {
        if(userModel == null){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }

        //实现model->dataobject方法
        UserDO userDO = convertFromModel(userModel);
        try{
            userDOMapper.insertRegister(userDO);
        }catch(DuplicateKeyException ex){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"注册失败 邮箱或手机号信息有重复");
        }
        userModel.setId(userDO.getId());
        UserPasswordDO userPasswordDO = convertPasswordFromModel(userModel);
        userPasswordDOMapper.insertSelective(userPasswordDO);
        try {
            //初始化用户数据
            ProductModel productModel = new ProductModel();
            productModel.setName("大工牌电风扇");
            productModel.setSerial("VPRO-300");
            productModel.setFactory("大连理工大学机械学院");
            productModel.setRegion("辽宁大连");
            productModel.setOrigin("中国大连");
            productModel.setAim("10t卡车柴油");
            productModel.setPower(3000);
            productModel.setDistance(200);
            productModel.setLife(5);
            productModel.setWeight(20);
            productModel.setParameter("未知");
            productModel.setComments("系统自带的学习数据");
            productModel.setUserId(userDO.getId());

            //存入产品信息 返回产品id
            Integer product_id = productService.submitProduct(productModel);
            //读取本地文件存入数据库
            File file = new File(FileUtils.path + FileUtils.sep + "大工牌电风扇.xlsx");
            InputStream in = new FileInputStream(file);
            EasyExcel.read(in, PartExcel.class, new ExcelListener(productService, product_id, userDO.getId(), productInfoDOMapper, productDOMapper)).sheet().doRead();
        } catch (Exception e) {
            throw new BusinessException(EmBusinessError.UNKNOWN_ERROR, "初始化用户数据失败");
        }

        return;
    }


    @Override
    public UserModel validateLogin(String TelOrEmail, String encrptPassword) throws BusinessException {
        UserDO userDO=new UserDO();
        UserPasswordDO userPasswordDO=new UserPasswordDO();
        UserModel userModel=new UserModel();
        //判断输入的是邮箱还是手机号
        if(judge(TelOrEmail)){
            userDO=userDOMapper.selectByEmail(TelOrEmail);
        }else{
            userDO=userDOMapper.selectByPhone(TelOrEmail);
        }

        if(userDO==null){
            throw new BusinessException(EmBusinessError.UNKNOWN_ERROR,"密码或账号错误!");
        }

        userPasswordDO =userPasswordDOMapper.selectByUserId(userDO.getId());

        if(userPasswordDO==null){
            System.out.println("userPasswordDO为空");
            throw new BusinessException(EmBusinessError.USER_LOGIN_FAIL);
        }

        userModel=convertFromDataObject(userDO,userPasswordDO);
        //比对用户信息内加密的密码是否和传输进来的密码相匹配
         if(!StringUtils.equals(encrptPassword,userModel.getPassword())){
              throw new BusinessException(EmBusinessError.USER_LOGIN_FAIL);
         }

        return userModel;
    }


    //判断是手机号还是邮件
    //true是邮箱
    //false为手机号
    private boolean judge(String TelOrEmail){
        char[] chars=TelOrEmail.toCharArray();
        for(char c:chars){
            if('@'==c) return true;
        }
        return false;
    }


    //存入UserPassword的信息
    private UserPasswordDO convertPasswordFromModel(UserModel userModel){
        if(userModel == null){
            return null;
        }
        UserPasswordDO userPasswordDO = new UserPasswordDO();
        userPasswordDO.setEncrptPassword(userModel.getPassword());
        userPasswordDO.setUserId(userModel.getId());
        return userPasswordDO;
    }

    //存入UserDo信息
    private UserDO convertFromModel(UserModel userModel){
        if(userModel == null){
            return null;
        }
        UserDO userDO = new UserDO();
        userDO.setEmail(userModel.getEmail());
        userDO.setName(userModel.getName());
        userDO.setTelphone(userModel.getTelphone());
        userDO.setUsername(userModel.getUsername());
        return userDO;
    }

    //合并UserDo和UserPassword的信息为UserModel
    private UserModel convertFromDataObject(UserDO userDO, UserPasswordDO userPasswordDO){
        if(userDO == null){
            return null;
        }
        UserModel userModel = new UserModel();
        userModel.setId(userDO.getId());
        userModel.setTelphone(userDO.getTelphone());
        userModel.setPassword(userPasswordDO.getEncrptPassword());
        userModel.setEmail(userDO.getEmail());
        userModel.setName(userDO.getName());
        userModel.setUsername(userDO.getUsername());
        return userModel;
    }
}
